package com.sprucetec.live.utils;

import com.sprucetec.live.constants.ZkCacheConstant;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @ClassName ZkUtil
 * @Description: zk缓存操作工具类
 * @Author Kenny
 * @Date 2020/4/26
 **/
@Component
public class ZkCacheUtil {

    @Autowired
    private ZooKeeper zooKeeper;

    /**
     * 给节点设置 Watcher 监听
     *
     * @param path
     * @throws Exception
     */
    public void setWatcher(String path, String type) throws Exception {
        if (zooKeeper.exists(path, true) != null) {
            zooKeeper.setData(path, (type + ZkCacheConstant.SPLIT + UUID.randomUUID().toString()).getBytes(), -1);
        } else {
            zooKeeper.create(path, ("init" + ZkCacheConstant.SPLIT + UUID.randomUUID().toString()).getBytes(),
                    ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            // 监听 zookeeper 售完节点
            zooKeeper.exists(path, true);
        }
    }
}
